package com.ck567.springbootnettyprotobufjava.server;

import com.ck567.springbootnettyprotobufjava.codec.MessageDecoder;
import com.ck567.springbootnettyprotobufjava.codec.MessageEncoder;
import com.ck567.springbootnettyprotobufjava.dispatcher.MessageDispatcher;
import com.ck567.springbootnettyprotobufjava.handler.idle.ServerIdleStateHandler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * @description: 初始化游戏场景通信协议并进行业务逻辑处理
 */
@ChannelHandler.Sharable
@Slf4j
@Component
public class MessageServerHandlerInitializer extends ChannelInitializer<Channel> {

    private final MessageEncoder messageEncoder;

    private final MessageDecoder messageDecoder;

    private final MessageDispatcher messageDispatcher;

//    private final ChannelStateHandler channelStateHandler;

    private final ServerIdleStateHandler serverIdleStateHandler;


    @Autowired
    public MessageServerHandlerInitializer(MessageEncoder messageEncoder, MessageDecoder messageDecoder, MessageDispatcher messageDispatcher, ServerIdleStateHandler serverIdleStateHandler) {
        this.messageEncoder = messageEncoder;
        this.messageDecoder = messageDecoder;
        this.messageDispatcher = messageDispatcher;
//        this.channelStateHandler = channelStateHandler;
        this.serverIdleStateHandler = serverIdleStateHandler;
    }

    @Override
    protected void initChannel(Channel channel) {
        channel.pipeline()
//                .addLast(serverIdleStateHandler)
                .addLast(new HttpServerCodec())
                .addLast(new ChunkedWriteHandler())
                .addLast(new HttpObjectAggregator(1024 * 64))
                .addLast(new WebSocketServerCompressionHandler())
                .addLast(new WebSocketServerProtocolHandler("/", null, true))
                .addLast(messageEncoder)
                .addLast(messageDecoder)
                .addLast(messageDispatcher);
//                .addLast(channelStateHandler);
    }
}